package club.xyes.zkh.ecommerce.commons.util;

import club.xyes.zkh.ecommerce.commons.exception.InternalServerErrorException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * Create by 郭文梁 2019/5/11 0011 14:39
 * QrCodeUtil
 * 二维码工具类
 *
 * @author 郭文梁
 * @data 2019/5/11 0011
 */
public class QrCodeUtil {
    /**
     * 创建二维码
     *
     * @param contents 内容
     * @param width    宽度
     * @param height   高度
     * @return bytes
     */
    public static byte[] creatRrCode(String contents, int width, int height) {
        String binary = null;
        HashMap<EncodeHintType, Object> hints = new HashMap<>(2);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(
                    contents, BarcodeFormat.QR_CODE, width, height, hints);
            // 1、读取文件转换为字节数组
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedImage image = toBufferedImage(bitMatrix);
            //转换成png格式的IO流
            ImageIO.write(image, "png", out);
            out.close();
            return out.toByteArray();
        } catch (WriterException | IOException e) {
            throw new InternalServerErrorException(e);
        }
    }

    /**
     * image流数据处理
     *
     * @author ianly
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }
}
